# backend/app/utils/file_utils.py
import os
import uuid
import shutil
from fastapi import UploadFile, HTTPException
from backend.app.config.settings import UPLOAD_DIR, MAX_UPLOAD_SIZE
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def save_upload_file(upload_file: UploadFile) -> str:
    """保存上传的文件并返回文件路径"""
    try:
        # 检查文件大小
        file_size = 0
        content = await upload_file.read()
        file_size = len(content)

        if file_size > MAX_UPLOAD_SIZE:
            raise HTTPException(status_code=413, detail=f"文件大小超过限制 ({MAX_UPLOAD_SIZE / 1024 / 1024}MB)")

        # 生成唯一文件名
        file_extension = os.path.splitext(upload_file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = os.path.join(UPLOAD_DIR, unique_filename)

        # 保存文件
        with open(file_path, "wb") as file:
            file.write(content)

        # 重置文件指针
        await upload_file.seek(0)

        logger.info(f"文件已保存: {file_path}")
        return file_path
    except Exception as e:
        logger.error(f"保存文件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"保存文件失败: {str(e)}")


def clean_old_files(directory=UPLOAD_DIR, max_age_days=1):
    """清理指定目录中的旧文件"""
    import time
    from datetime import datetime, timedelta

    now = time.time()
    cutoff = now - (max_age_days * 86400)

    files_removed = 0

    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            if os.path.getmtime(file_path) < cutoff:
                try:
                    os.remove(file_path)
                    files_removed += 1
                except Exception as e:
                    logger.error(f"删除文件失败 {file_path}: {str(e)}")

    logger.info(f"已清理 {files_removed} 个旧文件")
    return files_removed